package com.hbnu.system.utils;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hbnu.system.config.BaseException;
import com.hbnu.system.model.entity.User;
import com.hbnu.system.model.vo.InfoVO;
import com.hbnu.system.service.IUserService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class JwtUtils {

    @Autowired
    private static IUserService iUserService;
    //设置为1秒
    public static final long EXPIRE = 1000 * 60 * 60 * 24;  //token的过期时间 一天
    public static final String APP_SECRET = "ukc8BDbRigUDaY6pZZfWus2jZXXYHO";   //密钥 key

    public static String getJwtToken(String id, String roles) {

        String JwtToken = Jwts.builder()
                //头部
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")

                //payload
                //.setSubject("leslie") //代表这个JWT的主题，即它的所有人，这个是一个json格式的字符串，可以存放什么userid，roldid之类的，作为什么用户的唯一标志。
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))

                .claim("id", id)    //token的主体部分
                .claim("roles", roles)

                //signature
                .signWith(SignatureAlgorithm.HS256, APP_SECRET) //签名哈希
                .compact(); //拼接方法 将三个部分拼接起来形成一个String

        return JwtToken;
    }

    /**
     * 判断token是否存在与有效
     *
     * @param jwtToken
     * @return
     */
    public static boolean checkToken(String jwtToken) {
        if (StringUtils.isEmpty(jwtToken)) return false;
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }



    /**
     * getInfo
     * return :Map  uid 和 roles
     **/
    public static InfoVO getInfo(String value)  {
        if (StringUtils.isEmpty(value))
            throw new BaseException("认证失败");
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(value);
        Claims body = claimsJws.getBody();
            if(body.isEmpty()){
                throw new BaseException("认证失败");
            }
        String uid = (String)body.get("id");
        String role = (String)body.get("roles");
        InfoVO infoVO = new InfoVO();
        String[] strings = new String[1];
        strings[0] = role;
        infoVO.setUid(uid);
        infoVO.setRoles(strings);

        return infoVO;

    }

    /**
     * 根据token获取会员id
     *
     * @param request
     * @return
     */
    public static String getMemberIdByJwtToken(HttpServletRequest request) {
        String jwtToken = request.getHeader("X-Token");
        if (StringUtils.isEmpty(jwtToken)) return "";
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        return (String) claims.get("id");
    }




    public static boolean maketoken(String token) throws InstantiationException, IllegalAccessException {
        if (StringUtils.isEmpty(token))
            throw new BaseException("认证失败");
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        if(body.isEmpty()){
            throw new BaseException("认证失败");
        }
        String uid = (String)body.get("id");
        User user = IUserService.class.newInstance().getOne(Wrappers.lambdaQuery(User.class).eq(User::getUid, uid));
        user.setLogin_status(2);
        return true;
    }
}
